package it.fuesi.synotools.services.tasks.search;

import android.util.Log;

import it.fuesi.synotools.R;
import it.fuesi.synotools.adapters.BTSearchAdapter;
import it.fuesi.synotools.constants.ApiErrorCode;
import it.fuesi.synotools.helpers.FormatHelper;
import it.fuesi.synotools.model.base.ErrorObject;
import it.fuesi.synotools.model.btsearch.BTSearchClientParameters;
import it.fuesi.synotools.model.btsearch.BTSearchResultsDataObject;
import it.fuesi.synotools.model.btsearch.BTSearchResultsListResponse;
import it.fuesi.synotools.model.btsearch.BTSearchStartResponse;
import it.fuesi.synotools.services.client.BTSearchClient;
import it.fuesi.synotools.services.client.ServiceClientFactory;
import it.fuesi.synotools.services.tasks.base.BaseTask;

/**
 * Created by pascotto on 17/10/14.
 */
public class BTSearchTask extends BaseTask<BTSearchResultsListResponse, BTSearchResultsDataObject, BTSearchClientParameters> {

    private static final String TAG = BTSearchTask.class.getName();

    public BTSearchTask(BTSearchAdapter adapter){
        super(adapter);
    }


    @Override
    protected String getCacheKey() {
        return null;
    }

    @Override
    public BTSearchResultsListResponse run(BTSearchClientParameters params)  throws Exception{
            BTSearchClient client = ServiceClientFactory.getClient(BTSearchClient.class);

            final String taskid;
            long start = System.currentTimeMillis();

            Log.d(TAG, "Starting search --> ");
            publishProgress(getContext().getString(R.string.progress_start_search));
            BTSearchStartResponse startResponse = client.start(params.getKeyword());
            if(startResponse.isSuccess())
                taskid = startResponse.getData().getTaskid();
            else{
                taskid = null;
                //TODO: manage start error
            }

            boolean finished = false;

            BTSearchResultsListResponse resp = null;
            while(!finished) {
                publishProgress(getContext().getString(R.string.progress_query_search) + FormatHelper.formatTimeMillis(getContext(),System.currentTimeMillis() - start));
                resp = client.list(taskid);
                if (!resp.isSuccess()) {
                    resp.setSuccess(true);
                    resp.setData(new BTSearchResultsDataObject());
                    resp.setError(new ErrorObject());
                    resp.getError().setCode(ApiErrorCode.retry.getErrorCode());
                }else
                    finished = resp.getData().isFinished();

            }
            return resp;

    }


}
